<?php
//PingBuWang.Com
//Copyright (c) 2017~2099 http://www.pingbuwang.com All rights reserved.
namespace app\tag\model;

use think\Controller;
class TagsArticle extends Controller
{

    /**
     * 根据tag标签，更新数据
     * @param $tags
     * @return bool
     */
    public function updateByTags($tags) {

        if($tags == null ){
            return false;
        }

        // 删除掉已 经存在的该文章的匹配数据
        db('tagsArticle')->where(array('tags_id' =>$tags['id']) )->delete();

        // 读取所有有该关键字的文章
        $arts = db('articlesContent')->where( 'content like "%'.$tags['title'].'%" ')->select();

        foreach ($arts as $k1=>$v1){

            $content = htmlspecialchars_decode( $v1['content'] );
            $content = decodeHtmlForRichEditor( $content );

            $chapters = getChapterByKeyword($content,$tags['title']);

            // 处理每个文章中 tag关键字所在的句子，关键字在一篇文章中只关联 3 个句子
            $cnt = 0;
            foreach($chapters as $k2=>$v2){
                if($cnt++ > 3){
                    break;
                }
                if(strlen($v2)>300){
                    $v2 = mb_substr($v2,0,300);
                }
                db('tagsArticle')->insert(array('id'=>uuid(),'tags_id'=>$tags['id'],'article_id'=>$v1['id'],'article_chapter'=>$v2) );
            }
        }

        return true;
    }

}